import { Component } from 'react'
import { createRef } from 'react'
import avatar from '../assets/images/avatar.png'

export default class Form extends Component {
  state = {
    txt: '',
  }

  // 创建 ref 对象
  txtRef = createRef()

  // 控制文本域的值
  changeTxt = (e) => {
    this.setState({
      txt: e.target.value,
    })
  }

  onAdd = () => {
    const { txt } = this.state
    if (txt.trim() === '') {
      return this.txtRef.current.focus()
    }

    this.state.txt = ''

    // 调用父组件的方法
    this.props.addComment(txt)
  }

  render() {
    return (
      <div className="comment-send">
        <div className="user-face">
          <img className="user-head" src={avatar} alt="" />
        </div>
        <div className="textarea-container">
          <textarea
            cols="80"
            rows="5"
            placeholder="发条友善的评论"
            className="ipt-txt"
            value={this.state.txt}
            onChange={this.changeTxt}
            ref={this.txtRef}
          />
          <button className="comment-submit" onClick={this.onAdd}>
            发表评论
          </button>
        </div>
        <div className="comment-emoji">
          <i className="face"></i>
          <span className="text">表情</span>
        </div>
      </div>
    )
  }
}
